<template>
  <el-dialog v-model="isShowDialog"
             :before-close="handleClose"
             :title="title"
             draggable
             width="70%"
             append-to-body
  >
    <div class="justify-content items-center" style="margin-bottom: 15px">
      <div class="plan">
        <span class="information"></span>
        <span class="informationText">订单信息</span>
      </div>
    </div>
    <el-form :inline="true" ref="formRef" :disabled="isView" :model="saveParams" label-width="100px" :rules="rules">
      <div style="display: flex;flex-wrap: wrap">
        <el-col :span="6">
          <el-form-item label="出库单号">
            <el-input v-model="saveParams.outCode" placeholder="自动生成" disabled clearable/>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="仓库" prop="warehouseId">
            <el-select
                clearable
                v-model="saveParams.warehouseId"
                @change="changeWarehouse"
            >
              <template v-for="(item,index) in warehouseList" :key="index">
                <el-option :label="item.warehouseName" :value="item.warehouseId"></el-option>
              </template>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="收货人" prop="receiver">
            <el-input v-model="saveParams.receiver" placeholder="收货人" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号" prop="receiverPhone">
            <el-input v-model="saveParams.receiverPhone" :maxlength="11"
                      @input="saveParams.receiverPhone=limitIntNumber(saveParams.receiverPhone)" placeholder="手机号"
                      clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="省市区" prop="addressVal" style="width:95%">
            <el-cascader style="width:100%" ref="addressRef" v-model="saveParams.addressVal" :options="addressOptions"
                         :props="cascaderProps"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收货地址" prop="receiverAddress"  >
            <el-input v-model="saveParams.receiverAddress" placeholder="收货地址" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" style="width: 95%">
            <el-input type="textarea" :rows="3" v-model="saveParams.remark" placeholder="备注" clearable/>
          </el-form-item>
        </el-col>

      </div>

    </el-form>

    <div class="justify-content items-center" style="margin:15px 0">
      <div class="plan">
        <span class="information"></span>
        <span class="informationText">商品信息</span>
      </div>
    </div>
    <el-row v-if="!isView">
      <el-button icon="Plus" type="primary" @click="handleAdd">添加商品</el-button>
      <el-button icon="Delete" type="danger" @click="handleDel">删除所选</el-button>
    </el-row>
    <vxe-table
        ref="tableRef"
        border
        style="margin-top: 10px;"
        align="center"
        :data="tableList"
        height="300"
        :checkbox-config="{ trigger:'row'}"
        :row-config="{isCurrent: true, isHover: true}"
        :edit-rules="validRules"
        show-footer
        :footer-method="footerMethod"
    >
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column type="seq" width="80" title="序号"></vxe-column>
      <vxe-column field="skuCode" title="SKU编号"></vxe-column>
      <vxe-column field="skuName" title="商品名称"></vxe-column>
      <vxe-column field="skuImg" title="商品图片">
        <template #default="{row}">
          <ImagePreview v-if="row.skuImg" :width="150" :height="50" :src="row.skuImg"></ImagePreview>
        </template>
      </vxe-column>
      <vxe-column field="avlNum" title="可用库存数量"></vxe-column>
      <vxe-column field="outNum" title="出库数量">
        <template #header>
          <span style="color: red;">*</span>出库数量
        </template>
        <template #default="{row}">
          <el-input v-model="row.outNum" @change="countTotal(row)" :disabled="isView"
                    @input="row.outNum=limitIntNumber(row.outNum)" clearable/>
        </template>
      </vxe-column>
      <vxe-column field="unitPrice" title="出库单价">
        <template #header>
          <span style="color: red;">*</span>出库单价
        </template>
        <template #default="{row}">
          <el-input v-model="row.unitPrice" @change="countTotal(row)" :disabled="isView"
                    @input="row.unitPrice=limitNumber(row.unitPrice)" clearable/>
        </template>
      </vxe-column>
      <vxe-column field="totalPrice" width="120" title="出库总额">
        <template #header>
          <span style="color: red;">*</span>出库总额
        </template>
        <template #default="{row}">
          <el-input v-model="row.totalPrice" @change="contPice(row)" :disabled="isView"
                    @input="row.totalPrice=limitNumber(row.totalPrice)" clearable/>
        </template>
      </vxe-column>

    </vxe-table>

    <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" v-if="!isView" @click="clickSubmit"> 提交 </el-button>
          <el-button @click="handleClose">取消</el-button>
        </span>
    </template>

    <SelB2bDeliveGoods v-if="openSelDialog" :openSelDialog="openSelDialog"
                       :companyId="sysUserInfo.companyId"
                       :warehouseId="saveParams.warehouseId"
                       :filterData="tableList"
                       @closeSelDialog="closeSelDialog"></SelB2bDeliveGoods>
  </el-dialog>

</template>

<script setup>
import {addHandWork} from "@/api/scApi";
import {getCurrentInstance, onMounted, ref} from "vue";
import SelB2bDeliveGoods from "@/views/outStorage/b2BDelivery/component/selB2bDeliveGoods.vue";
import ImagePreview from "@/components/ImagePreview/index.vue";
import {getCompanySelect, getWarehouseSelect} from "@/api/system/user";
import SelB2bInstorageGoods from "@/views/inStorage/b2bInStorage/component/selB2bInstorageGoods.vue";

const {proxy} = getCurrentInstance()
let tableList = ref([])
let saveParams = ref({})
const validRules = ref({
  outNum: [
    {required: true, message: '出库数量不能为空'},
  ],
  unitPrice: [
    {required: true, message: '出库单价不能为空'},
  ],
  totalPrice: [
    {required: true, message: '出库总额不能为空'},
  ],
})

let addressOptions = ref([])//省市区数据源
let cascaderProps = ref({
  value: 'pcaId',
  label: 'name'
})
// 表单校验
const rules = ref({
  warehouseId: [{required: true, message: "仓库不能为空", trigger: "change"}],
  receiver: [{required: true, message: "收货人不能为空", trigger: "blur"}],
  receiverPhone: [{required: true, message: "手机号不能为空", trigger: "blur"}],
  addressVal: [{required: true, message: "省市区不能为空", trigger: "change"}],
  receiverAddress: [{required: true, message: "地址不能为空", trigger: "blur"}],
});

const props = defineProps({
  isShowDialog: {
    type: Boolean,
    default: false
  },
  title: {
    type: String
  },
  warehouseList: {type: Array},
  detailData: {type: Object},
  isView: {type: Boolean}
})

const emits = defineEmits(['cancel'])

function handleClose() {
  emits('cancel')
}

//添加商品事件处理
let openSelDialog = ref(false)

function handleAdd() {
  if(!saveParams.value.warehouseId  ){
    proxy.$modal.msgWarning("请先选择仓库!")
    return
  }
  openSelDialog.value = true
}

function closeSelDialog(data) {
  openSelDialog.value = false
  if (data) {
    tableList.value = [...tableList.value, ...data]
  }
}

onMounted(() => {
  if (JSON.stringify(props.detailData) != '{}') {
    saveParams.value = props.detailData
    tableList.value = props.detailData.detailList
    let addressList=[ props.detailData.pcaProvinceId,props.detailData.pcaCityId,props.detailData.pcaAreaId]
    saveParams.value.addressVal=addressList
  }
  let addressJSON = localStorage.getItem('addressJSON')
  if (addressJSON) {
    addressOptions.value = JSON.parse(addressJSON)
  }
  getWarehouse()
})

//删除所选
function handleDel() {
  let selRows = proxy.$refs.tableRef.getCheckboxRecords()
  let a = tableList.value
  let filtered = a.filter(obj => !selRows.some(bObj => bObj.skuId === obj.skuId));
  tableList.value = filtered
}

const clickSubmit = async () => {
  if(tableList.value.length===0){
    proxy.$modal.msgWarning("请先添加商品！")
    return
  }
  const $table = proxy.$refs.tableRef
  if ($table) {
    const errMap = await $table.validate(true)
    if (errMap) {
      console.log('校验失败！')
    } else {
      console.log('校验成功！')
      proxy.$refs.formRef.validate((valid) => {
        if (valid) {
          let pathLabels = proxy.$refs.addressRef.getCheckedNodes()[0].pathLabels
          let pathIds = saveParams.value.addressVal
          saveParams.value.pcaProvinceId = pathIds[0]//省ID
          saveParams.value.pcaProvinceName = pathLabels[0]//省名称
          saveParams.value.pcaCityId = pathIds[1]//市ID
          saveParams.value.pcaCityName = pathLabels[1]//市名称
          saveParams.value.pcaAreaId = pathIds[2]//区ID
          saveParams.value.pcaAreaName = pathLabels[2]//区名称
          saveParams.value.detailList=tableList.value
          addHandWork(saveParams.value).then(res => {
            if (res.code === 200) {
              proxy.$modal.msgSuccess('保存成功')
              emits('cancel', true)
            }
          })
        }
      })
    }
  }

}

//计算总额
function countTotal(row) {
  if (row.outNum && row.unitPrice) {
    row.totalPrice = (row.outNum * row.unitPrice).toFixed(2)
  }
  proxy.$refs.tableRef.updateFooter()
}

//计算单价
function contPice(row) {
  if (row.totalPrice && row.outNum) {
    row.unitPrice = (row.totalPrice / row.outNum).toFixed(2)
  }
  proxy.$refs.tableRef.updateFooter()
}

function footerMethod({columns, data}) {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return '合计'
      }
      if (['outNum', 'totalPrice'].includes(column.field)) {
        return sumNum(data, column.field)
      }
      return null
    })
  ]
}

const sumNum = (list, field) => {
  let count = 0
  list.forEach(item => {
    if (item[field]) {
      count += Number(item[field])
    }
  })
  return count.toFixed(2)
}

//获取仓库下拉数据
let warehouseList = ref([])
const sysUserInfo=JSON.parse(localStorage.getItem("userInfo"))
function getWarehouse(){
  getWarehouseSelect({'companyId':sysUserInfo.companyId}).then(res => {
    warehouseList.value = res.data
  })
}

function changeWarehouse(){
  tableList.value=[]
}
</script>

<style scoped lang="scss">

</style>